﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace SafetyRecord
{
    public partial class Options : Form
    {
        // 单位
        private const string R01 = "r01.xml";
        // 执法人员
        private const string R02 = "r02.xml";
        // 询问地址
        private const string R03 = "r03.xml";
        // 问答
        private const string R04 = "r04.xml";

        private int selectedIndex = -1;
        private int lawmanSelectedIndex = -1;

        //问答项顺序
        private int orderIndex = 3;
        public Options()
        {
            InitializeComponent();

        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            var name = ((Button)sender).Name;
            switch (name)
            { 
                case "AddOrgButton":
                    if (!string.IsNullOrWhiteSpace(textBox1.Text) || !string.IsNullOrEmpty(textBox1.Text))
                    {
                        listBox1.Items.Add(textBox1.Text);
                        textBox1.Text = string.Empty;
                    }
                    break;
                case "AddAddrButton":
                    if (!string.IsNullOrWhiteSpace(AskAddrTextBox.Text) || !string.IsNullOrEmpty(AskAddrTextBox.Text))
                    {
                        AskAddrListBox.Items.Add(AskAddrTextBox.Text);
                        AskAddrTextBox.Text = string.Empty;
                    }
                    break;
            }
            
            
        }

        private void AskAddrListBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right) return;
            var index = AskAddrListBox.IndexFromPoint(e.Location);
            if (index != ListBox.NoMatches)
            {
                contextMenuStrip2.Show(AskAddrListBox, e.Location);
                askingAddrSelectedIndex = index;
            }
        }

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right) return;
            var index = listBox1.IndexFromPoint(e.Location);
            if (index != ListBox.NoMatches)
            {
                DeleteMenu.Show(Cursor.Position);
                DeleteMenu.Visible = true;
                selectedIndex = index;
            }
            else
            {
                DeleteMenu.Visible = false;
            }
        }

        private int askingAddrSelectedIndex = -1;

        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right) return;

            var index = dataGridView1.HitTest(e.X, e.Y).RowIndex;
            var ignoredIndex = dataGridView1.Rows.Count - 1;
            if (index >= 0 && index < ignoredIndex)
            {
                contextMenuStrip1.Show(dataGridView1, new Point(e.X, e.Y));
                lawmanSelectedIndex = index;
            }
        }

        private void lawmanDelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lawmanSelectedIndex >= 0)
            {
                dataGridView1.Rows.RemoveAt(lawmanSelectedIndex);
            }
        }

        private void DelTool_Click(object sender, EventArgs e)
        {
            if (selectedIndex != -1)
                listBox1.Items.RemoveAt(selectedIndex);
        }

        private void AskingAddrDelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (askingAddrSelectedIndex >= 0)
            {
                AskAddrListBox.Items.RemoveAt(askingAddrSelectedIndex);
            }
        }

        private DataSet DataLoading(XmlStyle xml)
        {
            string xmlData = string.Empty;
            var fileName = string.Empty;
            switch (xml)
            { 
                case XmlStyle.Organize:
                    xmlData = "<XmlDS><OrgName><org></org></OrgName></XmlDS>";
                    fileName = R01;
                    break;
                case XmlStyle.Lawman:
                    xmlData = "<XmlDS><Lawman><name></name><id></id><org></org><job></job></Lawman></XmlDS>";
                    fileName = R02;
                    break;
                case XmlStyle.AskingAddr:
                    xmlData = "<XmlDS><AskingAddr><addr></addr></AskingAddr></XmlDS>";
                    fileName = R03;
                    break;
                case XmlStyle.AA:
                    xmlData = "<XmlDS><AA><ask></ask><answer></answer></AA></XmlDS>";
                    fileName = R04;
                    break;
                default:
                    xmlData = null;
                    break;
            }
            DataSet dataSet = new DataSet();
            if (!File.Exists(fileName))
            {
                StringReader xmlSR = new StringReader(xmlData);
                dataSet.ReadXml(xmlSR);
            }
            else
            {
                //var fn = System.Environment.CurrentDirectory + "\\" + fileName;
                dataSet.ReadXml(fileName);
            }

            return dataSet;
        }

        private void LawmanDataBinding()
        {
            var ds = DataLoading(XmlStyle.Lawman);
            ds.Tables[0].Columns[0].ColumnName = "姓名";
            ds.Tables[0].Columns[1].ColumnName = "执法证号";
            ds.Tables[0].Columns[2].ColumnName = "工作单位";
            ds.Tables[0].Columns[3].ColumnName = "职务";
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = "Lawman";

            // 设置GridView控件列宽百分比
            dataGridView1.Columns[0].FillWeight = 15;
            dataGridView1.Columns[1].FillWeight = 30;
            dataGridView1.Columns[2].FillWeight = 40;
            dataGridView1.Columns[3].FillWeight = 15;
        }

        private void AnswerDataBinding()
        {
            this.txtOrder.Text = this.orderIndex.ToString();
            this.txtName.Enabled = false;

            TreeNode root = new TreeNode("问答列表", 9, 9);
            root.Name = "root";
            this.treeView.Nodes.Add(root);
            this.treeView.SelectedNode = root;
            root.ExpandAll();


            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(R04);
            XmlNode xmlRoot = xmlDoc.SelectSingleNode("XmlDS");
            if (xmlRoot.HasChildNodes)
            {
                foreach (XmlNode wdNode in xmlRoot.ChildNodes)
                {
                    XmlElement wdEle = (XmlElement)wdNode;
                    int Order = int.Parse(wdEle.Attributes["Order"].Value);

                    TreeNode node = new TreeNode("问答项" + Order, 0, 1);
                    TreeNode wenNode = new TreeNode("问题项", 7, 7);
                    TreeNode daanNode = new TreeNode("回答项", 8, 8);
                    node.Name = "wenda";
                    wenNode.Name = "wenti";
                    daanNode.Name = "daan";
                    node.Nodes.Add(wenNode);
                    node.Nodes.Add(daanNode);
                    node.Tag = Order;
                    root.Nodes.Add(node);
                    
                    this.orderIndex = Order;

                    if (wdEle.HasChildNodes)
                    {
                        foreach (XmlNode contentNode in wdEle.ChildNodes)
                        {
                            TreeNode cNode = new TreeNode(contentNode.InnerText, 2, 2);
                            cNode.Name = "content";
                            if (contentNode.Name == "wenti")
                            {
                                wenNode.Nodes.Add(cNode);
                            }
                            else if (contentNode.Name == "daan")
                            {
                                daanNode.Nodes.Add(cNode);
                            }
                        }
                    }
                }
                this.txtOrder.Text = (++this.orderIndex).ToString();
                root.ExpandAll();
            }

        }

        private void OrgDataBinding()
        {
            var ds = DataLoading(XmlStyle.Organize);
            var table = ds.Tables[0];
            foreach (DataRow row in table.Rows)
            {
                listBox1.Items.Add(row["org"]);
            }
        }

        private void AddrDataBinding()
        {
            var ds = DataLoading(XmlStyle.AskingAddr);
            var table = ds.Tables[0];
            foreach (DataRow row in table.Rows)
            { 
                AskAddrListBox.Items.Add(row["addr"]);
            }
        }

        private void SaveAddrData()
        {
            DataTable addrTable = new DataTable("AskingAddr");
            DataColumn column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "addr";
            addrTable.Columns.Add(column);
            DataRow row;
            DataSet addrDS = new DataSet("XmlDs");
            addrDS.Tables.Add(addrTable);
            foreach (var item in AskAddrListBox.Items)
            {
                row = addrTable.NewRow();
                row["addr"] = item;
                addrTable.Rows.Add(row);
            }

            addrDS.WriteXml("r03.xml", XmlWriteMode.IgnoreSchema);
        }

        private void SaveOrgData()
        {
            DataTable orgTB = new DataTable("OrgName");
            DataColumn column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "org";
            orgTB.Columns.Add(column);
            DataRow row;
            DataSet orgDS = new DataSet("XmlDS");
            orgDS.Tables.Add(orgTB);
            foreach (var item in listBox1.Items)
            {
                row = orgTB.NewRow();
                row["org"] = item;
                orgTB.Rows.Add(row);
            }
            orgDS.WriteXml("r01.xml", XmlWriteMode.IgnoreSchema);
        }

        private void SaveAnswerData()
        {
            if(this.treeView.Nodes == null || this.treeView.Nodes.Count ==0)
                return;

            XmlDocument xmlDoc = new XmlDocument();
            XmlNode xmlDocNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(xmlDocNode);
            XmlNode viewer = xmlDoc.CreateElement("XmlDS");
            xmlDoc.AppendChild(viewer);


            foreach (TreeNode node in this.treeView.Nodes[0].Nodes)
            {
                XmlNode ItemNode = xmlDoc.CreateElement("WenDa");
                XmlAttribute Order = xmlDoc.CreateAttribute("Order");
                Order.Value = node.Tag.ToString();
                ItemNode.Attributes.Append(Order);  
                viewer.AppendChild(ItemNode);
                if (node.Nodes != null && node.Nodes.Count > 0)
                {
                    foreach (TreeNode wendaNode in node.Nodes)
                    {
                        if (wendaNode.Nodes != null && wendaNode.Nodes.Count > 0)
                        {
                            XmlNode WendaNode = null;
                            foreach (TreeNode aaNode in wendaNode.Nodes)
                            {
                                if (wendaNode.Name == "wenti")
                                    WendaNode = xmlDoc.CreateElement("wenti");
                                else if (wendaNode.Name == "daan")
                                    WendaNode = xmlDoc.CreateElement("daan");
                                WendaNode.InnerText = aaNode.Text;
                                ItemNode.AppendChild(WendaNode);
                            }
                        }
                    }
                }
            }
            xmlDoc.Save("r04.xml");  
        }

        private void Options_Load(object sender, EventArgs e)
        {
            OrgDataBinding();
            LawmanDataBinding();
            AddrDataBinding();
            AnswerDataBinding();
        }

        private void SaveLawmanData()
        {
            // 可将所有数据复制到 DataSet 中。
            DataSet lawmanDS = (DataSet)dataGridView1.DataSource;

            lawmanDS.WriteXml("r02.xml", XmlWriteMode.IgnoreSchema);

        }

        private void MainButtonClick(object sender, EventArgs e)
        {
            var name = (sender as Button).Name;
            switch (name)
            { 
                case "ConfirmButton":
                    SaveOrgData();
                    SaveLawmanData();
                    SaveAddrData();
                    SaveAnswerData();
                    this.Close();
                    break;
                case "CancelButton":
                    this.Close();
                    break;
            }
            
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.treeView.SelectedNode == null)
            {
                MessageBox.Show("请选择树节点后,再进行添加");
                return;
            }
            if (this.treeView.SelectedNode.Name == "root")
            {
                TreeNode node = new TreeNode("问答项" + this.txtOrder.Text, 0, 1);
                TreeNode wenNode = new TreeNode("问题项", 7, 7);
                TreeNode daanNode = new TreeNode("回答项", 8, 8);
                node.Name = "wenda";
                wenNode.Name = "wenti";
                daanNode.Name = "daan";
                node.Nodes.Add(wenNode);
                node.Nodes.Add(daanNode);
                node.Tag = this.orderIndex;
                this.treeView.SelectedNode.Nodes.Add(node);
                this.treeView.SelectedNode.ExpandAll();
                this.orderIndex = int.Parse(this.txtOrder.Text);
                this.txtOrder.Text = (++this.orderIndex).ToString();
                return;
            }else if (this.treeView.SelectedNode.Name == "wenti" || this.treeView.SelectedNode.Name == "daan")
            {
                if (!string.IsNullOrEmpty(this.txtName.Text))
                {
                    TreeNode contentNode = new TreeNode(this.txtName.Text.Trim(), 2, 2);
                    contentNode.Name = "content";
                    this.treeView.SelectedNode.Nodes.Add(contentNode);
                    this.treeView.SelectedNode.ExpandAll();
                    this.txtName.Text = "";
                }
            }
        }

        private void txtOrder_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (this.treeView.SelectedNode.Name == "root")
            {
                this.txtName.Enabled = false;
                this.txtName.Text = "";
                this.txtOrder.Enabled = true;
                this.txtOrder.Text = this.orderIndex.ToString();
                this.btnNew.Enabled = true;
                this.btnRest.Enabled = false;
                this.btnDel.Enabled = false;
            }else if (this.treeView.SelectedNode.Name == "wenda")
            {
                this.txtName.Enabled = false;
                this.txtName.Text = "";
                this.txtOrder.Enabled = true;
                this.txtOrder.Text = this.treeView.SelectedNode.Tag.ToString();
                this.btnNew.Enabled = false;
                this.btnRest.Enabled = true;
                this.btnDel.Enabled = true;
            }
            else if (this.treeView.SelectedNode.Name == "wenti" || this.treeView.SelectedNode.Name == "daan")
            {
                this.txtName.Enabled = true;
                this.txtName.Text = "";
                this.txtOrder.Enabled = false;
                this.txtOrder.Text = "";
                this.btnNew.Enabled = true;
                this.btnRest.Enabled = false;
                this.btnDel.Enabled = false;
            }
            else if (this.treeView.SelectedNode.Name == "content")
            {
                this.txtName.Enabled = true;
                this.txtOrder.Enabled = false;
                this.txtOrder.Text = "";
                this.txtName.Text = this.treeView.SelectedNode.Text;
                this.btnNew.Enabled = false;
                this.btnRest.Enabled = true;
                this.btnDel.Enabled = true;
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (this.treeView.SelectedNode != null)
            {
                if (this.treeView.SelectedNode.Name != "root" && this.treeView.SelectedNode.Name != "wenti" && this.treeView.SelectedNode.Name != "daan")
                {
                    this.treeView.SelectedNode.Remove();
                }
            }
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnNew_Click(sender, e);
            }
        }

        private void btnRest_Click(object sender, EventArgs e)
        {
            if (this.treeView.SelectedNode.Name == "wenda")
            {
                if (!string.IsNullOrEmpty(this.txtOrder.Text))
                {
                    this.treeView.SelectedNode.Tag = this.txtOrder.Text;
                    this.treeView.SelectedNode.Text = "问答项" + this.txtOrder.Text;
                }
            }
            else if (this.treeView.SelectedNode.Name == "content")
            {
                if (!string.IsNullOrEmpty(this.txtName.Text))
                {
                    this.treeView.SelectedNode.Text = this.txtName.Text.Trim();
                }
            }
        }
    }

    public enum XmlStyle
    {
        Organize,
        Lawman,
        AskingAddr,
        AA
    }
}
